package services;

import com.sun.mail.util.MailSSLSocketFactory;
import utils.QEncodeUtil;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 提供发送邮件操作的业务
 */
public class MailServices {

    //密钥匙
    private static String key = "123456";

    private String hostPath;
    private String username;

    private String getHost(String url) {
        String check = "^http://(.+?)/.*$";
        Pattern regex = Pattern.compile(check);
        Matcher m = regex.matcher(url);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }


    public MailServices(String requestUrl, String username) {
        this.hostPath = getHost(requestUrl) + "/mail?act=check&code=";
        this.username = username;
    }

    /**
     * 提供检查验证码的服务
     *
     * @param code 验证码
     * @return 返回true表示验证成功
     */
    public boolean checkMailCode(String code) throws Exception {
        //解码字符串
        String str = QEncodeUtil.aesDecrypt(code, MailServices.key);
        System.out.println("解密后的字符串：" + str);
        return username.equals(str);
    }

    /**
     * 发送邮件
     *
     * @param toMailAddress
     * @throws Exception
     */
    public void sendVertifyCode(String toMailAddress) throws Exception {
        //aes加密
        String code = QEncodeUtil.aesEncrypt(username, MailServices.key);
        System.out.println("code:" + code);
        sendMail(toMailAddress, code);
    }

    private void sendMail(String toMailAddress, String code) throws GeneralSecurityException, MessagingException, UnsupportedEncodingException {
        final Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        props.setProperty("mail.mime.charset", "utf-8");
        System.setProperty("mail.mime.charset", "utf-8");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);


        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session session = Session.getInstance(props, authenticator);

        MimeMessage msg = new MimeMessage(session);

        //邮件标题
        msg.setSubject("漫画网注册验证码");

        String s = "asdasdasd";

        //邮件正文
        // 设置邮件的内容体
        String code_url = URLEncoder.encode(code, "utf-8");
        String path = "http://" + hostPath + code_url;
        String content = "您的验证码是" + code + "-><a href='" + path + "'>" + path + "</a>";
        msg.setContent(content, "text/html;charset=UTF-8");
        msg.setFrom(new InternetAddress("921977939@qq.com"));

        Transport transport = session.getTransport();
        transport.connect("smtp.qq.com", "921977939@qq.com", "ewpganonwaokbebh");

//        List<Address> addresses=new ArrayList<Address>();
//        addresses.add(new InternetAddress(toMailAddress));
        transport.sendMessage(msg, new Address[]{new InternetAddress("921977939@qq.com"), new InternetAddress("weituotian@163.com")});
        transport.close();
    }

    private void sendMail2(String toMailAddress, String code) throws GeneralSecurityException, MessagingException, UnsupportedEncodingException {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.qq.com");
        // 发件人的账号
        props.put("mail.user", "921977939@qq.com");
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", "ewpganonwaokbebh");

        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));
        message.setFrom(form);

        // 设置收件人
        InternetAddress to = new InternetAddress("921977939@qq.com");
        message.setRecipient(Message.RecipientType.TO, to);

        // 设置抄送
        InternetAddress cc = new InternetAddress("921977939@qq.com");
        message.setRecipient(Message.RecipientType.CC, cc);

        // 设置密送，其他的收件人不能看到密送的邮件地址
        InternetAddress bcc = new InternetAddress("weituotian@163.com");
        message.setRecipient(Message.RecipientType.CC, bcc);

        // 设置邮件标题
        message.setSubject("测试邮件");

        // 设置邮件的内容体
        String code_url = URLEncoder.encode(code, "utf-8");
        String path = "http://" + hostPath + code_url;
        String content = "您的验证码是" + code + "-><a href='" + path + "'>" + path + "</a>";
        message.setContent(content, "text/html;charset=UTF-8");

        // 发送邮件
        Transport.send(message);
    }
}
